<script setup>
import { getAllSupplier } from '@/api/globalApi'

const tableData = ref([])
const fullName = ref('')
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emits = defineEmits(['update:modelValue', 'selectedSupplier'])

const tableColumn = ref([
  { label: '供应商编号', prop: 'ID' },
  { label: '供应商名称', prop: 'FullName' }
])

const selectedSupplier = ref( {})

const fetchOnce = () => {
  if (!selectedSupplier.value.ID) {
    ElMessage.warning({ message: '请选择供应商' })
    return
  }

  emits('selectedSupplier', selectedSupplier.value)
  closeDialog()
}

const rowClick = (row) => {
  selectedSupplier.value = row
}

// 关闭弹窗
const closeDialog = () => {
  fullName.value = ''
  selectedSupplier.value = {}
  emits('update:modelValue', false)
}

const loadData = async () => {
  const { data } = await getAllSupplier({ name: fullName.value })
  selectedSupplier.value = {}
  tableData.value = data
}

onMounted(loadData)
</script>

<template>
  <el-dialog
    :modelValue="$props.modelValue"
    title="选择供应商"
    @close="closeDialog"
    @open="loadData"
    class="select-customer-dialog"
  >
    <el-row class="search-bar" :gutter="10">
      <el-col :span="22">
        <el-input v-model="fullName" placeholder="请输入供应商名称" />
      </el-col>

      <el-col :span="2">
        <el-button type="primary" plain @click="loadData">载入</el-button>
      </el-col>
    </el-row>

    <ps-table :data="tableData" :tableColumn="tableColumn" @row-click="rowClick" :pageSize="10">
      <template #header>
        <el-table-column width="100" align="center">
          <template #default="scope">
            <el-radio :label="scope.row.ID" v-model="selectedSupplier.ID">{{ '' }}</el-radio>
          </template>
        </el-table-column>
      </template>
    </ps-table>

    <template #footer>
      <el-button type="primary" @click="fetchOnce">取回</el-button>
      <el-button @click="emits('update:modelValue', false)">关闭</el-button>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.search-bar {
  margin-bottom: 20px;
}
</style>
